<template>
	<view>
		<view class="background"></view>
		<navView navTitle="数据银行" backgroundColor="#008efe" titleColor="#fff" :isBack="true"></navView>

		<!-- 客户文件列表 -->
		<view class="customer-list">
			<view v-for="(item, index) in customerFiles" :key="index" class="customer-card">
				<view class="customer-header">
					<uni-icons type="person" size="24" color="#008EFF"></uni-icons>
					<text class="customer-name">{{ item.customer.name }}</text>
				</view>

				<!-- 文件列表 -->
				<view class="file-list">
					<view v-for="file in item.files" :key="file.id" class="file-item">
						<image class="file-icon" src="https://hfd.bjlzkj.com/static/list/file.png" />
						<view class="file-info">
							<text class="filename">{{ truncateFilename(file.filename) }}</text>
							<text class="file-meta">文件时间：{{ file.createtime }} | 文件大小：{{ formatFileSize(file.filesize)
								}}</text>
						</view>
						<view class="file-actions">
							<button class="action-btn view-btn" @click="handleView(file.url)">预览</button>
							<button class="action-btn download-btn" @click="handleDownload(file.url)">下载</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 分页状态 -->
		<view v-if="isLoading" class="loading-text">加载中...</view>
		<view v-if="isNoMore" class="no-more-text">已加载全部数据</view>
	</view>
</template>

<script>
import download from '@/util/filesdownload.js';
export default {
	data() {
		return {
			customerFiles: [],
			currentPage: 1,
			totalPages: 1,
			isLoading: false,
			isNoMore: false
		}
	},
	onLoad() {
		this.getUserFiles();
	},
	// onReachBottom() {
	//     if (!this.isNoMore && !this.isLoading) {
	//         this.currentPage++;
	//         this.getUserFiles(true);
	//     }
	// },
	methods: {
		async getUserFiles() {
			try {
				const res = await this.$request('/addons/qingdong/folder/getUserDatabaseFiles', 'GET');
				this.customerFiles = res.data;
			} finally {
				this.isLoading = false;
			}
			// if (this.isLoading) return;
			// this.isLoading = true;
			// try {
			// 	const res = await this.$request('/addons/qingdong/folder/getUserDatabaseFiles', 'GET', {
			// 		page: this.currentPage,
			// 		per_page: 5
			// 	});

			// 	// 合并客户数据
			// 	const mergeCustomers = (existing, incoming) => {
			// 		const customerMap = new Map();

			// 		// 添加已有客户到map
			// 		existing.forEach(c => customerMap.set(c.customer.id, c));

			// 		// 合并新客户数据
			// 		incoming.forEach(newCustomer => {
			// 			const existingCustomer = customerMap.get(newCustomer.customer.id);
			// 			if (existingCustomer) {
			// 				// 合并文件
			// 				existingCustomer.files = [...existingCustomer.files, ...newCustomer.files];
			// 			} else {
			// 				customerMap.set(newCustomer.customer.id, newCustomer);
			// 			}
			// 		});

			// 		return Array.from(customerMap.values());
			// 	};

			// 	if (isLoadMore) {
			// 		// 合并新旧客户数据
			// 		this.customerFiles = mergeCustomers(this.customerFiles, res.data.data);
			// 	} else {
			// 		this.customerFiles = res.data.data;
			// 	}

			// 	this.totalPages = res.data.last_page;
			// 	this.isNoMore = this.currentPage >= this.totalPages;
			// } finally {
			// 	this.isLoading = false;
			// }
		},
		truncateFilename(name) {
			const maxLength = 15; // 最大显示长度
			return name.length > maxLength ? `${name.substr(0, maxLength)}...` : name;
		},
		// 新增时间格式化方法
		formatTime(timestamp) {
			const date = new Date(timestamp * 1000);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 
            ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},
		// 新增文件大小格式化
		formatFileSize(bytes) {
			if (bytes === 0) return '0 B';
			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
		},
		// 下载文件
		handleDownload(url) {
			download.downloadFun(url);
		},
		handleView(url) {
			// 检查文件是否已下载
			uni.showLoading({ title: '正在打开...' });  // 新增加载提示
			uni.downloadFile({
				url: url,
				success: function (res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: encodeURI(filePath),
						showMenu: true,
						success: function (res) {
							uni.hideLoading();  // 隐藏加载提示
							console.log('打开文档成功', res);
						},
						fail: function (err) {
							uni.hideLoading();  // 隐藏加载提示
							console.error('打开文档失败', err);
						}
					});
				},
				fail: (err) => {
					uni.hideLoading();  // 隐藏加载提示
					console.error('下载失败', err);
					uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
				}
			});
		},
	}
}
</script>

<style lang="less">
.customer-list {
	padding: 30rpx;

	.customer-card {
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.05);

		.customer-header {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.customer-name {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				margin-left: 20rpx;
			}
		}

		.file-list {
			padding: 0 30rpx;

			.file-item {
				display: flex;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1rpx dashed #eee;

				&:last-child {
					border-bottom: none;
				}

				.file-icon {
					width: 80rpx;
					height: 80rpx;
					margin-right: 30rpx;
				}

				.file-info {
					flex: 1;

					.filename {
						font-size: 28rpx;
						color: #333;
						display: -webkit-box;
						-webkit-line-clamp: 2; // 显示两行
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
						line-height: 1.4; // 调整行高
						max-height: 3em; // 两行高度（1.4*2 ≈ 2.8em）
					}

					.file-meta {
						font-size: 24rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}

				.file-actions {
					display: flex;
					gap: 20rpx;

					.action-btn {
						height: 50rpx;
						line-height: 50rpx;
						padding: 0 30rpx;
						border-radius: 25rpx;
						font-size: 24rpx;

						&.view-btn {
							background: #f0f7ff;
							color: #008EFF;
							border: 1rpx solid #008EFF;
						}

						&.download-btn {
							background: #008EFF;
							color: #fff;
						}
					}
				}
			}
		}
	}
}

.loading-text,
.no-more-text {
	text-align: center;
	padding: 30rpx;
	color: #999;
	font-size: 24rpx;
}
</style>